"""
数据库初始化脚本
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from sqlalchemy import create_engine
from app.database import Base, engine
from app.models import *
from app.config import settings


def init_database():
    """初始化数据库"""
    print("开始初始化数据库...")
    
    # 创建所有表
    Base.metadata.create_all(bind=engine)
    print("数据库表创建完成")
    
    # 插入基础数据
    insert_basic_data()
    print("基础数据插入完成")
    
    print("数据库初始化完成！")


def insert_basic_data():
    """插入基础数据"""
    from sqlalchemy.orm import sessionmaker
    from datetime import datetime
    from passlib.context import CryptContext
    
    # 密码加密上下文
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        # 插入部门数据
        departments = [
            {"name": "运营部门", "description": "负责流量获取和分配"},
            {"name": "售前转化部门", "description": "负责学员转化和销售"},
            {"name": "售后服务部门", "description": "负责学员服务和教学"}
        ]
        
        for dept_data in departments:
            existing = session.query(Department).filter(Department.name == dept_data["name"]).first()
            if not existing:
                department = Department(**dept_data)
                session.add(department)
        
        session.commit()
        print("部门数据插入完成")
        
        # 插入科目数据
        subjects = [
            {"name": "Python", "description": "Python编程语言"},
            {"name": "Java", "description": "Java编程语言"},
            {"name": "前端开发", "description": "HTML、CSS、JavaScript"},
            {"name": "数据分析", "description": "数据分析和机器学习"},
            {"name": "网络安全", "description": "网络安全和渗透测试"}
        ]
        
        for subject_data in subjects:
            existing = session.query(Subject).filter(Subject.name == subject_data["name"]).first()
            if not existing:
                subject = Subject(**subject_data)
                session.add(subject)
        
        session.commit()
        print("科目数据插入完成")
        
        # 插入地区数据
        regions = [
            {"name": "华北地区", "province": "北京", "city": "北京市"},
            {"name": "华东地区", "province": "上海", "city": "上海市"},
            {"name": "华南地区", "province": "广东", "city": "深圳市"},
            {"name": "西南地区", "province": "四川", "city": "成都市"}
        ]
        
        for region_data in regions:
            existing = session.query(Region).filter(Region.name == region_data["name"]).first()
            if not existing:
                region = Region(**region_data)
                session.add(region)
        
        session.commit()
        print("地区数据插入完成")
        
        # 插入流量渠道数据
        channels = [
            {"name": "抖音", "type": "external", "description": "抖音平台推广"},
            {"name": "微信", "type": "external", "description": "微信朋友圈推广"},
            {"name": "百度", "type": "external", "description": "百度搜索推广"},
            {"name": "内部推荐", "type": "internal", "description": "内部员工推荐"},
            {"name": "朋友推荐", "type": "internal", "description": "朋友推荐"}
        ]
        
        for channel_data in channels:
            existing = session.query(TrafficChannel).filter(TrafficChannel.name == channel_data["name"]).first()
            if not existing:
                channel = TrafficChannel(**channel_data)
                session.add(channel)
        
        session.commit()
        print("流量渠道数据插入完成")
        
        # 插入系统配置数据
        configs = [
            {"config_key": "system_name", "config_value": "CRM系统", "description": "系统名称"},
            {"config_key": "max_upload_size", "config_value": "10485760", "description": "最大上传文件大小（字节）"},
            {"config_key": "default_page_size", "config_value": "20", "description": "默认分页大小"}
        ]
        
        for config_data in configs:
            existing = session.query(SystemConfig).filter(SystemConfig.config_key == config_data["config_key"]).first()
            if not existing:
                config = SystemConfig(**config_data)
                session.add(config)
        
        session.commit()
        print("系统配置数据插入完成")
        
        # 创建默认管理员账户
        admin_employee = session.query(Employee).filter(Employee.employee_no == "admin").first()
        if not admin_employee:
            # 获取第一个部门（运营部门）
            first_department = session.query(Department).first()
            if first_department:
                admin_employee = Employee(
                    employee_no="admin",
                    name="系统管理员",
                    department_id=first_department.id,
                    position="系统管理员",
                    phone="13800000000",
                    email="admin@crm.com",
                    password_hash=pwd_context.hash("admin123"),  # 默认密码：admin123
                    status="active"
                )
                session.add(admin_employee)
                session.commit()
                print("默认管理员账户创建成功！")
                print("用户名: admin")
                print("密码: admin123")
            else:
                print("警告: 没有找到部门，无法创建管理员账户")
        
    except Exception as e:
        session.rollback()
        print(f"插入基础数据时出错: {e}")
        raise
    finally:
        session.close()


if __name__ == "__main__":
    init_database()
